<template>
    <div class='goods'>
        <div class="container">
            <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" class="search-con">
                <el-row>
                    <el-col :span="24" style="margin-bottom: 15px;">
                        <el-form-item>
                            <el-button size="mini" v-for="item, index in btnList" :key="index" @click="changeTab(item, index)"
                                :type="curLine == index ? 'primary' : 'default'">
                                {{ item.dictLabel }}</el-button>
                        </el-form-item>
                    </el-col>
                    <el-form-item label="" prop="key_name" label-width="0px">
                        <el-input v-model="queryParams.key_name" placeholder="商品名称" clearable size="small" />
                    </el-form-item>
                    <el-form-item label="" prop="key_cate_name" label-width="0px">
                        <el-cascader style="width: 300px;" class="form-item-cascader" :key="resetCascader"
                                    ref="myCascader" v-model="cate_ids" placeholder="请选择分类" :options="cateList"
                                    :props="optionProps" @change="e => handleChange(e, cate_ids)"
                                    clearable></el-cascader>
                        <!-- <el-input v-model="queryParams.key_cate_name" placeholder="分类名称" clearable size="small" /> -->
                    </el-form-item>
                    <!-- <el-form-item label="" prop="key_cate_name" label-width="0px">
                        <el-input v-model="queryParams.key_cate_name" placeholder="二级分类名称" clearable size="small" />
                    </el-form-item> -->
                    <el-form-item label="" prop="key_staff_name" label-width="0px">
                        <el-input v-model="queryParams.key_staff_name" placeholder="负责员工名称" clearable size="small" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
                            v-hasPermi="['customer:manage:export']">导出
                        </el-button>
                    </el-form-item>
                </el-row>
            </el-form>
            <el-row :gutter="10" class="mb8">
                <el-col :span="22">
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd()"
                        v-hasPermi="['customer:manage:add']">
                        新增商品</el-button>
                    <el-button type="primary" size="mini" @click="handleMultiDelete()"
                        v-hasPermi="['product:manage:add']">批量删除</el-button>
                    <!-- curRow={};title = '新增商品';handleShow = 'add'; -->
                    <span style="margin-left: 25px; font-size:110%;font-weight: bold;color:#30B08F;">共{{ listCount
                    }}个</span>
                </el-col>
                <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
            <el-table border v-loading="loading" :data="tableList" ref="tableList" v-tableHeight
                :height="tableList && tableList.length > 0 ? '900px' : '120px'" @selection-change="handleSelectionChange"
                @row-click="toggleSelection">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="排序" align="center" width="80">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.sort" @keyup.native="scope.row.sort = handleNum0(scope.row.sort)"
                            @blur="sortTab(scope.row)" clearable size="small" />
                    </template>
                </el-table-column>
                <el-table-column label="编号" align="center" prop="code" />
                <el-table-column label="商品图片" align="center" prop="cover">
                    <template slot-scope="scope">
                        <div v-if="scope.row.cover" class="img-list">
                            <el-image style="width: auto; height: 45px;" :src="scope.row.cover"
                                :preview-src-list="[scope.row.cover]">
                            </el-image>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="商品名称" align="center" prop="name" />
                <el-table-column label="商品分类" align="center" prop="cate_name" />
                <el-table-column label="销售价格" align="center" prop="price_selling" />
                <!-- <el-table-column label="负责员工" align="center" prop="resp_staff_id">
                    <template slot-scope="scope">
                        <span>
                            {{ scope.row.resp_staff_id ? staffList.find(item => item.id == scope.row.resp_staff_id).name : '' }}
                        </span>
                    </template>
                </el-table-column> -->
                <!-- <el-table-column label="价格/货号" align="center" prop="mobile" /> -->
                <!-- <el-table-column label="标签" align="center" prop="mobile" />
                <el-table-column label="排序" align="center" prop="mobile" />
                <el-table-column label="SKU库存" align="center" prop="mobile" />
                <el-table-column label="销量" align="center" prop="mobile" /> -->
                <el-table-column label="创建时间" align="center" prop="create_at" />
                <el-table-column label="是否首页推荐" align="center" prop="state_home" v-if="statusShow">
                    <template slot-scope="scope">
                        <span>
                            {{ selectDictLabel(statusList1, scope.row.state_home) }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="状态" align="center" prop="status" v-if="statusShow">
                    <template slot-scope="scope">
                        <span>
                            {{ selectDictLabel(statusList, scope.row.status) }}
                        </span>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="审核状态" align="center" prop="mobile">
                    <template slot-scope="scope">
                        <span class="text-link" @click="toAudit()">审核状态审核</span>
                    </template>
                </el-table-column> -->
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <!-- @click="title='详情';customerId=String(scope.row.id);handleShow='detail'" -->
                        <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)"
                            v-hasPermi="['marketSales:admit:edit']">
                            编辑
                        </el-button>
                        <el-button size="mini" type="text" @click="toAudit(scope.row)"
                            v-hasPermi="['marketSales:admit:edit']">
                            入库
                        </el-button>
                        <el-button v-if="statusShow" size="mini" type="text" icon="el-icon-document"
                            @click="toDetail(scope.row)" v-hasPermi="['marketSales:admit:detail']">
                            查看详情
                        </el-button>
                        <!-- <el-button size="mini" type="text" @click="handleStaff(scope.row)"
                            v-hasPermi="['product:manage:unRacking']">选择负责员工
                        </el-button> -->
                        <el-button v-if="scope.row.status == 0" size="mini" type="text" @click="handleAble(scope.row)"
                            v-hasPermi="['user:staff:stop']">上架
                        </el-button>
                        <el-button v-if="scope.row.status == 1 && statusShow" size="mini" type="text"
                            @click="handleAble(scope.row)" v-hasPermi="['user:staff:start']">下架
                        </el-button>
                        <el-button v-if="scope.row.state_home == 0" size="mini" type="text" @click="handleSet(scope.row)"
                            v-hasPermi="['user:staff:stop']">设置首页推荐
                        </el-button>
                        <el-button v-if="scope.row.state_home == 1 && statusShow" size="mini" type="text"
                            @click="handleSet(scope.row)" v-hasPermi="['user:staff:start']">取消首页推荐
                        </el-button>
                        <el-button v-if="!statusShow" size="mini" type="text" @click="handleCheck(scope.row)"
                            v-hasPermi="['user:staff:start']">审核上架
                        </el-button>
                        <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">
                            删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="pageCount > 0" :pageCount="pageCount" :page.sync="queryParams.page"
                :limit.sync="queryParams.limit" @pagination="getList" />

            <!-- 新增 -->
            <add v-if="handleShow == 'add' || handleShow == 'edit' || handleShow == 'detail'" :title="title"
                :handleShow="handleShow" :data="curRow" :submitShow="submitShow" @close="handleShow = ''" @load="getList" />
            <!-- :customerId="customerId" customerId=null; -->
            <audit v-if="handleShow == 'audit'" :data="stockRow" @close="handleShow = ''" @load="getList" />

            <el-dialog title="选择负责员工" visible v-if="handleShow == 'assign'" @close="close()" width="65%" append-to-body
                :close-on-click-modal="false">
                <el-form ref="form" :model="form" :rules="rules" label-width="120px" v-loading="formLoading">
                    <el-form-item prop="staff_id" label="选择负责员工">
                        <el-select v-model="form.staff_id" placeholder="请选择负责员工" clearable size="small">
                            <el-option v-for="dict in staffList" :key="dict.id" :label="dict.name" :value="dict.id" />
                        </el-select>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="close()">取 消</el-button>
                    <el-button type="primary" @click="submit" :disabled="formLoading">确 定</el-button>
                </span>
            </el-dialog>

        </div>
    </div>
</template>
<script>
import throttle from 'lodash.throttle'
import { getGoodsLists, getGoodsInfo, setGoodsStatus, delGoodsInfo, getHousingInfo, getRespStaffLists, setrespStaff, setGoodsHome, setGoodsSort, getGoodsCateLists } from "@/api/goods/goods"
import { goodStatus, yesNo } from "@/api/dictionary"
import add from "./handle/add"
import audit from "./handle/auditDetails"

export default {
    name: 'goods',
    components: {
        add,
        audit
    },
    data() {
        return {
            showSearch: true,
            loading: false,
            total: 0,
            pageCount: 0,
            queryParams: {
                page: 1,
                limit: 20,
                key_status: '',
                key_name: '',
                key_cate_name: '',
                key_staff_name: '',
            },
            tableList: [
                {}
            ],
            timeType: [{
                dictLabel: '发货时间',
                dictValue: 0
            },
            {
                dictLabel: '下单时间',
                dictValue: 1
            }],
            statusList: goodStatus,
            statusList1: yesNo,
            // statusList: [
            //     {
            //         dictLabel: '待付款',
            //         dictValue: 0
            //     },
            //     {
            //         dictLabel: '待发货',
            //         dictValue: 1
            //     }, {
            //         dictLabel: '已发货',
            //         dictValue: 2
            //     },
            //     {
            //         dictLabel: '已完成',
            //         dictValue: 3
            //     }, {
            //         dictLabel: '已关闭',
            //         dictValue: 4
            //     }
            // ],
            selectData: [],
            btnList: [
                {
                    dictLabel: '全部商品',
                    dictValue: ''
                },
                {
                    dictLabel: '已上架',
                    dictValue: 1
                },
                {
                    dictLabel: '未上架',
                    dictValue: -1
                },
                {
                    dictLabel: '待审核',
                    dictValue: 0
                },
                // {
                //     dictLabel: '未通过',
                //     dictValue: 4
                // },
            ],
            curLine: 0,
            handleShow: "",
            submitShow: null,
            title: "",
            statusShow: true,
            statusString: '',
            curRow: {},
            stockRow: {},
            formLoading: false,
            form: {
                code: '',

            },
            rules: {
                staff_id: [{ required: true, message: '请选择负责员工', trigger: 'blur' }],
            },
            staffList: [],
            listCount: '',
            codeList: [],
            codes: '',
            cateList: [],
            cateIds: [],
            optionProps: {
                value: 'id',
                label: 'name',
                disabled: "disabled",
                children: 'children',
                emitPath: true,
            },
            resetCascader: 0,
            cate_ids:[],
        }
    },
    created() {
        this.getList();
        this.getRespStaffLists();
        this.getCateList();
    },
    methods: {
        getList() {
            this.loading = true;
            getGoodsLists(this.queryParams).then(res => {
                this.tableList = res.data ? res.data.lists : [];
                this.pageCount = res.data.pageCount;
                this.listCount = res.data.listsCount;
                this.loading = false;
            });
        },
        getCateList(){
            getGoodsCateLists().then(res =>{
                this.cateList = res.data
            this.cateList.forEach(e => {
                if (e && e.children) {
                    e.disabled = false
                } else {
                    e.disabled = true
                }
            });
            })

        },
        handleChange(id, cate_ids){
            console.log(id, cate_ids, "id, cate_ids")
            this.queryParams.key_cate_id = cate_ids[1]
            this.getList();
        },
        toAudit(row) {
            getHousingInfo({ code: row.code }).then(res => {
                this.title = "商品入库"
                this.stockRow = res.data;
                this.handleShow = 'audit';
            })
        },
        changeTab(item, index) {
            this.curLine = index
            this.queryParams.key_status = item.dictValue
            let num = item.dictValue
            this.statusString = num.toString()
            if (this.statusString === '' || this.statusString === '1' || this.statusString === "-1") {
                this.statusShow = true
            } else if (this.statusString === '0') {
                this.statusShow = false
            }
            this.getList()
        },
        /** 导出按钮操作 */
        handleExport() {
            const queryParams = this.queryParams;
            this.$confirm('是否确认导出所有数据项?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(function () {
                // return exportBanner(queryParams);
            }).then((response) => {
                // this.download(response.msg);
            });
        },
        toggleSelection(row) {
            this.$refs.tableList.toggleRowSelection(row);
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.selectData = selection;
        },

        toggleSelection(row) {
            this.$refs.tableList.toggleRowSelection(row);
        },

        // 多选框选中数据
        handleMultiDelete(selection) {
            this.codeList = [];
            this.selectData = this.$refs.tableList.selection;
            console.log(this.selectData, 'xuanzhongdata')
            if (this.selectData.length == 0) {
                this.$confirm('请选择商品进行批量操作', "警告", {
                    confirmButtonText: "确定",
                    type: "warning"
                })
            } else if (this.selectData.length > 0) {
                for (let i = 0; i < this.selectData.length; i++) {
                    let code = this.selectData[i].code
                    this.codeList.push(code)
                    console.log(this.codeList, 'codes')
                }
                this.codes = this.codeList.join(",")
                console.log(this.codes, '传参灿灿')
                let params = {
                    codes: this.codes
                }
                this.$confirm('是否确认批量删除选中商品?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function () {
                    return delGoodsInfo(params);
                }).then(() => {
                    this.getList();
                    this.msgSuccess("删除成功");
                })

            }
        },

        sortTab(row) {
            console.log(row, 123)
            setGoodsSort({
                sort: row.sort,
                code: row.code
            }).then(res => {
                if (res.code == 1) {
                    this.msgSuccess("操作成功");
                    this.getList()
                }
            })
        },

        handleQuery() {
            this.queryParams.page = 1;
            this.getList();
        },
        resetQuery() {
            this.resetForm("queryForm");
            this.queryParams.key_cate_id = '',
            this.cate_ids = [],
            this.handleQuery();
        },
        toDetail(row) {
            getGoodsInfo({ code: row.code }).then(res => {
                this.title = "详情"
                this.curRow = res.data;
                this.handleShow = 'detail';
            })
        },
        handleCheck(row) {
            getGoodsInfo({ code: row.code }).then(res => {
                this.title = "审核上架"
                this.curRow = res.data;
                this.handleShow = 'edit';
                this.submitShow = true;
            })
        },
        handleEdit(row) {
            getGoodsInfo({ code: row.code }).then(res => {
                this.curRow = res.data;
                this.title = "编辑"
                this.handleShow = 'edit';
                this.submitShow = false;
            })
        },
        handleAdd() {
            getGoodsInfo().then(res => {
                console.log(res.data.code)
                this.curRow = res.data;
                this.title = "创建商品"
                this.handleShow = 'add';
            })
        },
        handleAble(row) {
            let label = row.status == 0 ? '上架' : '下架';
            this.$confirm(`是否将“${row.name}”${label}?`, "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return setGoodsStatus({ code: row.code });
            }).then(() => {
                this.getList();
                this.msgSuccess(`${label}成功`);
            })
        },
        handleSet(row) {
            let label = row.state_home == 0 ? '设置' : '取消';
            this.$confirm(`是否将“${row.name}”${label}首页推荐?`, "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return setGoodsHome({ code: row.code });
            }).then(() => {
                this.getList();
                this.msgSuccess(`${label}成功`);
            })
        },
        handleDelete(row) {
            this.$confirm('是否确认删除' + '"' + row.name + '"' + '?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return delGoodsInfo({ codes: row.code });
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            })
        },

        getRespStaffLists() {
            getRespStaffLists().then(res => {
                this.staffList = res.data;
                console.log(this.staffList, '员工列表')
            })
        },
        handleStaff(row) {
            this.handleShow = 'assign';
            this.getRespStaffLists();
            this.form.code = row.code;
        },
        close() {
            this.curRow = {}
            this.form = {}
            this.handleShow = ""
        },
        submit: throttle(function () {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.formLoading = true;
                    setrespStaff(this.form).then(res => {
                        this.msgSuccess("操作成功！");
                        this.close()
                        this.formLoading = false;
                        this.getList();
                    }).catch(() => {
                        this.formLoading = false;
                    })
                }
            })
        }, 1000, { trailing: false }),
    },
}

</script>
<style scoped lang='scss'></style>